﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using KL.UFrame.Core.Log;
using KL.UFrame.Core.Unity;
using Newtonsoft.Json;

namespace KL.UFrame.Core.Authorization
{
    /// <summary>
    /// Api角色管理器
    /// By：杨超
    /// </summary>
    public static class K9ActionRolesManager
    {
        private static readonly Dictionary<string, Dictionary<string, string[]>> ActionRoles;
        

        static K9ActionRolesManager()
        {

            var roleFile = HttpContext.Current.Server.MapPath("~/App_Data/roles.json");
            try
            {
                string text = string.Empty;
                using (StreamReader reader = new StreamReader(roleFile, Encoding.Default))
                {
                    text = reader.ReadToEnd();
                }
                ActionRoles = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string[]>>>(text);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("加载api角色配置表失败", ex);
            }
        }

        public static string[] GetRoles(string controllerName, string actionName)
        {
            controllerName = controllerName.ToLower();
            actionName = actionName.ToLower();

            if(!ActionRoles.ContainsKey(controllerName)) return null;
            var actions = ActionRoles[controllerName];
            if (!actions.ContainsKey(actionName)) return null;
            return actions[actionName];
        }
    }
}